<template>
  <div class="app-container">
    <!-- 搜索表单部分 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="派单编码" prop="workOrderCode">
        <el-input v-model="queryParams.workOrderCode" placeholder="请输入派单编码" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="生产指令编号" prop="orderCode">
        <el-input v-model="queryParams.orderCode" placeholder="请输入生产指令编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="派单人" prop="dispatchPerson">
        <el-input v-model="queryParams.dispatchPerson" placeholder="请输入派单人nickName" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="接单人员" prop="receivePerson">
        <el-input v-model="queryParams.receivePerson" placeholder="请输入接单人员" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 顶部按钮栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['product:dispatch:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格部分 -->
    <el-table v-loading="loading" :data="dispatchList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="派单编码" align="center" prop="workOrderCode" />
      <el-table-column label="派单名称" align="center" prop="workName" />
      <el-table-column label="生产指令编号" align="center" prop="orderCode" />
      <el-table-column label="派单人" align="center" prop="dispatchPerson" />
      <el-table-column label="接单人员" align="center" prop="receivePerson" />
      <el-table-column label="接单用户ID" align="center" prop="userId" />
      <el-table-column label="派单时间" align="center" prop="dispatchTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dispatchTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="接单时间" align="center" prop="receiveTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.receiveTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="派单状态" align="center" prop="dispatchStatus">
        <template slot-scope="scope">
          <!-- 修复1：表格状态显示，用自定义映射匹配数字和文字 -->
          <span :class="getStatusClass(scope.row.dispatchStatus)">
            {{ getStatusText(scope.row.dispatchStatus) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="驳回原因" align="center" prop="rejectReason" />
      <el-table-column label="派单备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
            v-hasPermi="['product:dispatch:query']">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页部分 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="生产指令编号" prop="orderCode">
          <el-input v-model="form.orderCode" placeholder="请输入生产指令编号" />
        </el-form-item>

        <el-form-item label="">
          <el-button size="mini" type="text" icon="el-icon-document" @click="handleViewInstruction(form.orderCode)"
            v-hasPermi="['product:getOrderByCode:orderCode']">查看指令</el-button>
        </el-form-item>

        <el-form-item label="派单名称" prop="workName">
          <el-input v-model="form.workName" placeholder="派单名称" readonly />
        </el-form-item>

        <el-form-item label="派单人" prop="dispatchPerson">
          <el-input v-model="form.dispatchPerson" placeholder="请输入派单人" />
        </el-form-item>
        <el-form-item label="接单人员" prop="receivePerson">
          <el-input v-model="form.receivePerson" placeholder="请输入接单人员" />
        </el-form-item>
        <el-form-item label="接单用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入接单用户ID" />
        </el-form-item>
        <el-form-item label="接单时间" prop="receiveTime">
          <el-date-picker clearable v-model="form.receiveTime" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择接单时间">
          </el-date-picker>
        </el-form-item>

        <!-- 派单状态下拉框（修复2：value改为数字类型，与后端返回匹配） -->
        <el-form-item label="派单状态" prop="dispatchStatus">
          <el-radio-group v-model="form.dispatchStatus">
            <el-radio :label="1">待接单</el-radio>
            <el-radio :label="2">已接单</el-radio>
            <el-radio :label="3">已完成</el-radio>
            <el-radio :label="4">有异常</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="驳回原因" prop="rejectReason" v-if="form.dispatchStatus === 4">
          <el-input v-model="form.rejectReason" placeholder="请输入驳回原因" />
        </el-form-item>

        <el-form-item label="派单备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入派单备注" />
        </el-form-item>
      </el-form>


      <!-- 弹窗底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <!-- 只保留修改模式的确定按钮（移除新增相关逻辑） -->
        <el-button type="primary" @click="submitForm" v-if="mode === 'edit'">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

      <!-- 生产指令详情弹窗 -->
      <instruction-detail-dialog ref="instructionDialog" />

    </el-dialog>
  </div>
</template>

<script>
import { listDispatch, getDispatch, updateDispatch } from "@/api/product/dispatch"
import InstructionDetailDialog from './InstructionDetailDialog.vue'

export default {
  name: "Dispatch",
  dicts: ['production_status'],
  components: { InstructionDetailDialog },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      dispatchList: [],
      title: "",
      open: false,
      mode: "view", // view-查看，edit-编辑，add-新增
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        workOrderCode: null,
        orderCode: null,
        dispatchPerson: null,
        receivePerson: null,
      },
      form: {
        // 修复4：初始化dispatchStatus为数字类型（与后端匹配）
        dispatchStatus: 1
      },
      rules: {
        receivePerson: [
          { required: true, message: '请输入接单人员', trigger: 'blur' }
        ],
        userId: [
          { required: true, message: '请输入接单用户ID', trigger: 'blur' }
        ],
        dispatchStatus: [
          { required: true, message: '请选择派单状态', trigger: 'change' }
        ],

        rejectReason: [
          {
            required: true,
            message: '请输入驳回原因',
            trigger: 'blur',
            // 仅当状态为“有异常”时，校验必填
            validator: (rule, value, callback) => {
              if (this.form.dispatchStatus === 4 && !value) {
                callback(new Error('请输入驳回原因'));
              } else {
                callback();
              }
            }
          }
        ]

      },
      // 修复5：定义状态映射表，统一管理数字和文字的对应关系
      statusMap: [
        { value: 1, text: '待接单', class: 'status-pending' },
        { value: 2, text: '已接单', class: 'status-received' },
        { value: 3, text: '已完成', class: 'status-completed' },
        { value: 4, text: '有异常', class: 'status-error' }
      ]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 查看生产指令详情
    handleViewInstruction(orderCode) {
      if (!orderCode) {
        this.$message.warning('生产指令编号不存在')
        return
      }
      this.$refs.instructionDialog.show(orderCode)
    },

    /** 查询派单列表 */
    getList() {
      this.loading = true
      listDispatch(this.queryParams).then(response => {
        this.dispatchList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        workOrderCode: null,
        orderCode: null,
        dispatchPerson: null,
        receivePerson: null,
        userId: null,
        dispatchTime: null,
        receiveTime: null,
        dispatchStatus: null, // 重置后仍为数字类型
        rejectReason: null,
        remark: null,
        createTime: null,
        updateTime: null,
        isDelete: null
      }
      this.resetForm("form")
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 查看方法 */
    // handleView中确保类型为数字
    handleView(row) {
      getDispatch(row.id).then(response => {
        const data = response.data || {};
        this.form = {
          ...data,
          dispatchStatus: Number(data.dispatchStatus) // 强制转数字
        };
        this.open = true;
        this.mode = "edit";
      });
    },

    /** 接单操作 */
    doReceive() {
      if (!this.form.receivePerson) {
        this.$message.warning('请输入接单人员')
        return
      }
      if (!this.form.userId) {
        this.$message.warning('请输入接单用户ID')
        return
      }

      // 修复7：接单状态设为数字2
      this.form.receiveTime = new Date().format("yyyy-MM-dd")
      this.form.dispatchStatus = 2

      addDispatch(this.form).then(response => {
        this.$modal.msgSuccess("接单成功")
        this.open = false
        this.getList()
      }).catch(() => {
        this.$modal.msgError("接单失败，请重试")
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 只处理修改操作（必须有id才提交）
          if (this.form.id != null) {
            updateDispatch(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            // 防止无id时提交（非修改场景）
            this.$modal.msgError("数据异常，无法提交")
          }
        }
      })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('product/dispatch/export', {
        ...this.queryParams
      }, `dispatch_${new Date().getTime()}.xlsx`)
    },

    /** 禁用表单所有输入元素 */
    disableForm() {
      const formElements = this.$refs.form.$el.querySelectorAll(
        'input, select, el-input, el-select, el-date-picker'
      )
      formElements.forEach(el => {
        el.disabled = true
        if (el.__vue__) el.__vue__.disabled = true
      })
    },

    /** 恢复表单可编辑 */
    enableForm() {
      const formElements = this.$refs.form.$el.querySelectorAll(
        'input, select, el-input, el-select, el-date-picker'
      )
      formElements.forEach(el => {
        el.disabled = false
        if (el.__vue__) el.__vue__.disabled = false
      })
    },

    // 修复8：根据状态值获取对应的文字（表格显示用）
    getStatusText(value) {
      const status = this.statusMap.find(item => item.value === Number(value))
      return status ? status.text : '未知状态'
    },

    // 修复9：根据状态值获取对应的样式（表格显示用，可选）
    getStatusClass(value) {
      const status = this.statusMap.find(item => item.value === Number(value))
      return status ? `el-tag el-tag--small ${status.class}` : 'el-tag el-tag--small el-tag--gray'
    }
  }
}
</script>

<!-- 修复10：添加状态标签样式（可选，优化显示） -->
<style scoped>
.status-pending {
  background-color: #e6a23c;
  color: #fff;
}

.status-received {
  background-color: #409eff;
  color: #fff;
}

.status-completed {
  background-color: #67c23a;
  color: #fff;
}

.status-error {
  background-color: #f56c6c;
  color: #fff;
}

.el-tag--small {
  padding: 2px 8px;
  font-size: 12px;
  border-radius: 4px;
}
</style>